package com.yu.dv.service;

import com.yu.dv.autoconfigure.DashScopeClient;
import com.yu.dv.autoconfigure.properties.NaturalLanguageSqlProperties;
import com.yu.dv.entity.req.NaturalLanguageRequest;
import com.yu.dv.entity.res.ExecutionResult;
import com.yu.dv.entity.res.SqlGenerationResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class NaturalLanguageToSqlService {

    private final InputValidator inputValidator;
    private final TextProcessor textProcessor;
    private final DashScopeClient dashScopeClient;
    private final SqlExecutor sqlExecutor;
    private final NaturalLanguageSqlProperties properties;

    public NaturalLanguageToSqlService(InputValidator inputValidator, TextProcessor textProcessor,
                                       DashScopeClient dashScopeClient, SqlExecutor sqlExecutor,
                                       NaturalLanguageSqlProperties properties) {
        this.inputValidator = inputValidator;
        this.dashScopeClient = dashScopeClient;
        this.textProcessor = textProcessor;
        this.sqlExecutor = sqlExecutor;
        this.properties = properties;
    }

    public SqlGenerationResponse processNaturalLanguage(NaturalLanguageRequest request) {
        long startTime = System.currentTimeMillis();

        try {
            InputValidator.ValidationResult validation = inputValidator.validate(request.getNaturalLanguage());
            if (!validation.isValid()) {
                return SqlGenerationResponse.error(validation.getErrorMessage());
            }

            String prompt = textProcessor.preprocessInput(request.getNaturalLanguage(), request.getTableSchema());
            String aiResponse = dashScopeClient.generateSqlWithRetry(prompt, properties.getMaxRetry());
            String generatedSql = textProcessor.extractSqlFromResponse(aiResponse);

            if (generatedSql.isEmpty()) {
                return SqlGenerationResponse.error("无法从AI响应中提取有效的SQL语句");
            }

            ExecutionResult executionResult = sqlExecutor.executeDdl(generatedSql);

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("generatedSql", generatedSql);
            responseData.put("executionResult", executionResult.getData());
            responseData.put("executionMessage", executionResult.getMessage());

            SqlGenerationResponse response = SqlGenerationResponse.success(
                    generatedSql,
                    executionResult.getMessage(),
                    responseData
            );
            response.setExecutionTime(System.currentTimeMillis() - startTime);

            log.info("自然语言转SQL处理完成，耗时: {}ms", response.getExecutionTime());
            return response;

        } catch (Exception e) {
            log.error("处理自然语言转SQL失败", e);
            SqlGenerationResponse errorResponse = SqlGenerationResponse.error(
                    null,
                    "处理失败: " + e.getMessage()
            );
            errorResponse.setExecutionTime(System.currentTimeMillis() - startTime);
            return errorResponse;
        }
    }
}